import { Request } from "../../../../utils/request.js";
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    buxian: false,//不限选项开关状态
    addressName: new Array(), //初始化地址数据库字段名
    addressId: new Array(),   //初始化地址数据库字段名id
    match_button_show: 1,   //默认是单一满足
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.ShowStatusList = true;   //开启选择地址数据接口
    const eventChannel = this.getOpenerEventChannel();
    let that = this;
    eventChannel.on('basic', (data) => {
      that.basic_info = data;
      //上一页面传递过来的所有数据内容
      let basicParam = this.basic_info;
      //上一页面某一列数据
      this.basicArrList = basicParam.arr_data;
      //上一页面某一列索引
      this.arr_data_index = basicParam.index;
      //上一页面选项类型 1是普通选项，2是地址选项
      this.choose_type = basicParam.choose_type;

      //获取当前字段所有的选项，并且显示用户所选择的id
      new Request('basic/Get_Register_Basic/GetParamList').request(
        () => {
          return {
            openid: app.globalData.openid,
            root_id: basicParam.arr_data.root_id,
            root_name: basicParam.arr_data.att_name,
          }
        },
        (res) => {
          let arr = res.data.data;
          console.log(basicParam)
          console.log(basicParam.arr_data)
          //1是单选列表，2是多选列表，3是地址列表
          var type = basicParam.list_type;
          if(own_choose_id != undefined){
            var own_choose_id = basicParam.arr_data.own_choose_id.toString();
            if (own_choose_id != 0 && type == 1 && this.choose_type == 1) {
              for (let i = 0, l = arr.length; i < l; i++) {
                if (own_choose_id.indexOf(arr[i].id) != -1) {
                  arr[i].status = 1;
                } else {
                  arr[i].status = 2;
                }
              }
            }
          }
          

          
          if(wan_choose_id != undefined){
            var wan_choose_id = basicParam.arr_data.wan_choose_id;
            var wan_root_name = basicParam.arr_data.wan_root_name.toString();
            if (wan_choose_id != 0 && type == 2 && this.choose_type == 1) {
              wan_choose_id = wan_choose_id.split(',');
              for (let i = 0, l = arr.length; i < l; i++) {
                let wan_choose_id_str = arr[i].id.toString();
                if (wan_choose_id.indexOf(wan_choose_id_str) != -1) {
                  arr[i].status = 1;
                } else {
                  arr[i].status = 2;
                }
              }
              this.basic_id = wan_choose_id;
              this.basic_text = wan_root_name.split(',');
            }
          }
          

          //地址选项列表
          if (this.choose_type == 2 && type == 2) {
            this.type = type
            arr.unshift({ 'areaId': 0, 'areaName': '不限', 'status': 2 });
          }
          if (this.choose_type == 2) {
            type = 3;
          }
          if (type == 2) {
            console.log(arr)
            arr.unshift({ 'id': 0, 'att_name': '不限', 'status': 2 });
          }
          // if (this.choose_type == 2) {
          //   arr.unshift({'areaId':0,'areaName':'不限','status':2});
          // }
          this.setData({
            optlist: arr,
            //判断用户选择的类型  1是我的基本信息，是单选列表  2是想找的基本信息，是多选列表
            listtype: type,
            //根id
            root_id: basicParam.arr_data.root_id
          });
        },
      );
    });
  },
  /**
   * 单选
   */
  select_btn2: function (e) {
    //获得选项值下标
    let index = e.currentTarget.dataset.index;
    let arr = 'optlist';
    for (let i = 0, l = this.data[arr].length; i < l; i++) {
      if (index == i) {
        this.data[arr][index].status = 1;
      } else {
        this.data[arr][i].status = 2;
      }
    }
    this.setData({
      optlist: this.data[arr],
      danlist: this.data[arr][index],
      choose_status: 'dan'
    });
    this.basicArrList['own_choose_id'] = this.data[arr][index].id;
    this.basicArrList['own_root_name'] = this.data[arr][index].att_name;
    console.log(this.basicArrList)
    return;

  },
  //确认保存
  save_btns: function (e) {
    //单选修改
    if (this.data.choose_status == 'dan') {
      console.log(this.data.root_id)
      new Request('basic/update/Update_Basic/updateOwn').request(
        () => {
          return {
            userid: app.globalData.userid,
            root_id: this.data.root_id,
            own_choose_id: this.data.danlist.att_upid,
            own_root_name: this.data.danlist.att_name,
          }
        },
        (res) => {
          console.log(res)
        }
      )
    }
    //多选修改
    if (this.data.choose_status == 'duo') {
      console.log(this.data.duolist)
      new Request('basic/update/Update_Basic/updateWan').request(
        () => {
          return {
            userid: app.globalData.userid,
            root_id: this.data.root_id,
            wan_choose_id: this.data.duolist.wan_choose_id,
            wan_root_name: this.data.duolist.wan_root_name,
            match_status: this.data.match_button_show
          }
        },
        (res) => {
          console.log(res)
        }
      )
    }
    const eventChannel = this.getOpenerEventChannel();
    let data = {
      'index': this.arr_data_index,
      'arr_data': this.basicArrList,
    }
    eventChannel.emit('back', data);
      wx.showToast({
        title: '',
        icon: 'loading',
        duration: 100,
      })
      setTimeout(()=>{
        wx.navigateBack({
          delta: 1
        });
      },101);
  },
  /**
   * 多选
   */
  select_btn: function (e) {
    console.log(this.data)
    let arr = 'optlist';
    let index = e.currentTarget.dataset.index;
    //选择不限的时候
    if (index == 0) {
      for (let i = 1, l = this.data[arr].length; i < l; i++) {
        this.data[arr][i].status = 3;
      }
      this.data[arr][0].status = 1;
      this.setData({
        optlist: this.data[arr],
      });
      this.basicArrList['wan_choose_id'] = this.data[arr][index].id;
      this.basicArrList['wan_root_name'] = this.data[arr][index].att_name;
      // return; //这里的return就是退出整个方法了,下面的语句都没有执行
    }
    let newArr = 'basic_id';
    let newArr_text = 'basic_text';
    if (this.data[arr][0].status == 1) {
      for (let i = 0, l = this.data[arr].length; i < l; i++) {
        this.data[arr][i].status = 2;
      }
      this.data[arr][0].status = 3;
      this[newArr] = [];
      this[newArr_text] = [];
    }

    if (this.data[arr][index].status != 1) {
      //未选择
      this.data[arr][index].status = 1;
      if (this[newArr] == undefined) {
        //id
        let strId = this.data[arr][index].id.toString();
        this[newArr] = [];
        this[newArr].push(strId);
        //name
        this[newArr_text] = [];
        this[newArr_text].push(this.data[arr][index].att_name);
      } else {
        //id
        let strId = this.data[arr][index].id.toString();
        let strIndex = this[newArr].indexOf(strId);
        if (strIndex == -1) {
          this[newArr].push(strId);
        }
        //name
        let valueIndex_text = this[newArr_text].indexOf(this.data[arr][index].att_name);
        if (valueIndex_text == -1) {
          this[newArr_text].push(this.data[arr][index].att_name);
        }
      }
    } else {
      //以选择
      this.data[arr][index].status = 2;
      //id
      if (this[newArr] != undefined) {
        let strId = this.data[arr][index].id.toString();
        let strIndex = this[newArr].indexOf(strId);
        if (strIndex != -1) {
          this[newArr].splice(strIndex, 1);
        }
        console.log(this[newArr]);
      }
      //name
      if (this[newArr_text] != undefined) {
        let valueIndex_text = this[newArr_text].indexOf(this.data[arr][index].att_name);
        if (valueIndex_text != -1) {
          this[newArr_text].splice(valueIndex_text, 1);
        }
      }
    }
    // this.setData({
    //   optlist: this.data[arr],
    //   choose_status: 'duo'
    // });
    this.basicArrList['wan_choose_id'] = this[newArr].join(',');
    this.basicArrList['wan_root_name'] = this[newArr_text].join('/');
    this.setData({
      optlist: this.data[arr],
      choose_status: 'duo',
      duolist: this.basicArrList
    });
    return;
  },
  //多选的单一满足 | 全部满足
  match_button: function (event) {
    if (event.currentTarget.dataset.buttonid == 'single') {
      this.basicArrList['match_status'] = 1;
      this.setData({
        match_button_show: 1,
      });
      console.log(event);
      return;
    }
    if (event.currentTarget.dataset.buttonid == 'double') {
      this.basicArrList['match_status'] = 2;
      this.setData({
        match_button_show: 2,
      });
      console.log(event);
      return;
    }

    console.log(event.currentTarget.dataset.buttonid);
  },
  /**
   * 地址选择按钮
   */
  select_btn3: function (param) {
    console.log('店了')
    //当地址选择为不限的时候
    if (param.currentTarget.dataset.areaname == '不限') {
      this.data.addressId = param.currentTarget.dataset.areaid;
      this.data.addressName = param.currentTarget.dataset.areaname;

      this.basicArrList['wan_choose_id'] = this.data.addressId;
      this.basicArrList['wan_root_name'] = this.data.addressName;
      console.log(this.data)
      console.log(this.basicArrList)
      //点击想找的
      new Request('basic/update/Update_Basic/updateWan').request(
        () => {
          return {
            userid: app.globalData.userid,
            root_id: this.data.root_id,
            wan_choose_id: this.data.addressId,
            wan_root_name:  this.data.addressName,
            match_status: this.data.match_button_show
          }
        },
        (res) => {
          console.log(res)
        }
      )
      this.save_btns()
      return;
    }
    if (this.ShowStatusList == true) {
      this.ShowStatusList = false;
      console.log(param.currentTarget.dataset.areaid);
      console.log(this.data.addressId);
      //判断是否重复插入
      // if (this.data.addressId.indexOf(param.currentTarget.dataset.areaid) != -1) {
      //   return;
      // }
      // if (this.data.addressName.indexOf(param.currentTarget.dataset.areaname) != -1) {
      //   return;
      // }
      this.data.addressId.push(param.currentTarget.dataset.areaid);
      this.data.addressName.push(param.currentTarget.dataset.areaname);

      new Request('Zyregister/GetAddressShi').request(
        () => {
          return {
            areaId: param.currentTarget.dataset.areaid
          }
        },
        (res) => {
          if (res.data.data.length != 0) {
            if (this.type == 2) {
              res.data.data.unshift({ 'areaId': 0, 'areaName': '不限', 'status': 2 });
            }
            this.setData({
              optlist: res.data.data,
              listtype: 3,    //判断用户选择的类型  1是我的基本信息，是单选列表  2是想找的基本信息，是多选列表
            })
          } else if (res.data.data.length == 0) {
            console.log(this.data.addressName.toString());
            let addresName = this.data.addressName.toString()
            let addresName_wan = this.data.addressName.toString().replace(/,/g, "/");

            let addressId = this.data.addressId.toString();

            if (this.basic_info.list_type == 1) {
              this.basicArrList['own_choose_id'] = addressId;
              this.basicArrList['own_root_name'] = addresName;

              //点击我的
              new Request('basic/update/Update_Basic/updateOwn').request(
                () => {
                  return {
                    userid: app.globalData.userid,
                    root_id: this.data.root_id,
                    own_choose_id: addressId,
                    own_root_name: addresName,
                  }
                },
                (res) => {
                  console.log(res)
                }
              )

            } else {
              this.basicArrList['wan_choose_id'] = addressId;
              this.basicArrList['wan_root_name'] = addresName_wan;

              //点击想找的
              new Request('basic/update/Update_Basic/updateWan').request(
                () => {
                  return {
                    userid: app.globalData.userid,
                    root_id: this.data.root_id,
                    wan_choose_id: addressId,
                    wan_root_name: addresName_wan,
                    match_status: this.data.match_button_show
                  }
                },
                (res) => {
                  console.log(res)
                }
              )

            }
            this.save_btns();
            // const eventChannel = this.getOpenerEventChannel();
            // eventChannel.emit('basicinfo', {optid: addressId , name: addresName , index: this.basic.index , listtype: this.basic.listtype});
            // wx.showToast({
            //   title: '',
            //   icon: 'loading',
            //   duration: 100,
            // })
            // setTimeout(()=>{
            //   wx.navigateBack({
            //     delta: 1
            //   });
            // },101);
          }
          this.ShowStatusList = true;
        }
      );
      wx.showToast({
        title: '加载中...',
        icon: 'loading',
        duration: 2000,
        mask: true
      })
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})